package com.shop.Control;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import java.util.Date;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.JSON2.json.JSONObject;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.shop.service.MerchantServiceImpl;
import com.shop.util.BeanUtil;
import com.shop.util.FileUploadUtil;
import com.shop.util.FormAjaxUtil;

/**
 * 
 * <b>商铺管理上传商品信息<b>
 * @author 威 
 * <br>2017年12月
 *
 */
public class MerchantManageAddGoodsAction extends SuperActionSupport {
	/** 
	 * @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么) 
	 */ 
	private static final long serialVersionUID = 6179199551109915025L;
	/**
	 * 
	 * 添加商品
	 * 
	 */
	private File file ; 
	private String fileFileName ;
	private String fileContentType ;
	private String callbackObj ;
	
	public String getCallbackObj() {
		return callbackObj;
	}

	public void setCallbackObj(String callbackObj) {
		this.callbackObj = callbackObj;
	}

	public void setFile(File file){
		this.file = file ;
	}
	public File getFile(){
		return file ;
	}
	
	public void setFileFileName(String fileFileName){
		this.fileFileName = fileFileName ;
	}
	public String getFileFileName(){
		return fileFileName ;
	}
	
	public void setFileContentType(String fileContentType){
		this.fileContentType = fileContentType ;
	}
	public String getFileContentType(){
		return fileContentType ;
	}
	
	public String execute(){
		System.out.println("添加商品") ;
		
		String fileName = null ;
		if(file != null){
			System.out.println("上传文件") ;
			if(fileFileName.endsWith(".png"))
				fileName = new Date().getTime() + ".png" ;
			else
				fileName = new Date().getTime() + ".jpg" ;
			System.out.println("fileUploadUtil") ;
			MerchantServiceImpl merchantServiceImpl = (MerchantServiceImpl) BeanUtil.getBean("merchantServiceImpl") ;
			ActionContext ct = ActionContext.getContext() ;
			Map parameterMap = ct.getParameters() ;
			merchantServiceImpl.addGoods((Integer) ct.getSession().get("merchant_id") ,
					((String[]) parameterMap.get("goodsName"))[0],
					Double.valueOf(((String[]) parameterMap.get("goodsPrice"))[0]),
					((String[]) parameterMap.get("goodsSizes"))[0],
					((String[]) parameterMap.get("goodsColors"))[0],
					fileName) ;
			try {
				writeTo(file, fileName) ;
				System.out.println("上传文件完毕") ;
				print(FormAjaxUtil.successAccess(callbackObj, "upload/" + fileName)) ;
			} catch (IOException e) {
				print(FormAjaxUtil.successAccess(callbackObj, "false")) ;
				e.printStackTrace() ;
			}
		}
		return SUCCESS ;
	}
	public void writeTo(File filee, String fileName) throws IOException{
		String uploadPath = ServletActionContext.getServletContext().getRealPath("/upload") ;
		FileUploadUtil fileUploadUtil = (FileUploadUtil) BeanUtil.getBean("fileUploadUtil") ;
		fileUploadUtil.wirteTo(file, uploadPath, fileName) ;
	}
}
